package cn.dapeng.features;

import java.util.concurrent.CountDownLatch;

/**
 * 门栓
 */
public class CountDownLatch_T01 {

    public static final int TEST_TIME = 100;

    public static Thread[] threads = new Thread[TEST_TIME];
    public static int sum = 0;

    public static void useCountDownLatch() throws InterruptedException {

        CountDownLatch latch = new CountDownLatch(TEST_TIME);
        for (int i = 0; i < TEST_TIME; i++) {
            final int j = i;
            threads[i] = new Thread(() -> {
                sum += j;
                latch.countDown();
            });

            threads[i].start();
        }

        latch.await();
        System.out.println("useCountDownLatch sum = " + sum);
    }

    public static void useJoin() throws InterruptedException {
        for (int i = 0; i < TEST_TIME; i++) {
            final int j = i;
            threads[i] = new Thread(() -> {
                sum += j;
            });

            threads[i].start();
            threads[i].join();
        }

        System.out.println("useJoin sum = " + sum);
    }

    public static void main(String[] args) throws InterruptedException {
        useCountDownLatch();
        useJoin();
    }
}
